<?php

namespace app\web\controller;

use AlibabaCloud\Cdn\V20180510\SetWaitingRoomConfig;
use app\common\controller\Api;
use app\common\controller\Smscm;
use app\common\model\Factor;
use app\common\model\Fenorder;
use app\common\service\PrintService;
use app\common\service\RoomCostService;
use app\common\service\SendVoiceMsgService;
use app\web\controller\Express;
use think\Db;
use app\common\service\FeiEPrintService;


/**
 * 手牌结账控制器
 * @package app\index\controller
 */
class HandRoomCheckOut extends Auth
{
    public $noNeedLogin = [];


    /**
     * 获取用户房间结账列表
     */
    public function check_out()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['hand_card_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $margeRoom = Db::name('qt_hand_card_marge')->where('id', $getData['hand_card_id'])->value('marge');
            if (!empty($margeRoom)) {
                //有合并房间
                $margeRoom = explode(',', $margeRoom);
                //项目
                $project = Db::name('qt_order')
                    ->field('o.id')
                    ->alias('o')
                    ->leftJoin('qt_room r', 'r.id = o.room_id')
                    ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                    ->where(['pay_status' => '1'])
                    ->whereIn('hand_card_id', $margeRoom)
                    ->order('o.id desc')
                    ->select();
                $projectRes = Db::name('qt_order_project')
                    ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id,room_id,hand_card_id,order_id')
                    ->whereIn('order_id', array_column($project, 'id'))
                    ->whereNotNull('engineer_id')
                    ->where('is_change', '1')
                    ->select();
                foreach ($projectRes as $key => $value) {
                    $projectRes[$key]['order_id'] = $value['order_id'];
                    $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                    $projectRes[$key]['room_name'] = Db::name('qt_room')->where('id', $value['room_id'])->value('name');
                    $projectRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                }

                //插入房费
                foreach ($margeRoom as $k => $room_id) {
                    $room_data = Db::name('qt_room')->where('id', $room_id)->find();
                    RoomCostService::saveCostOrder($room_data['store_id'], $room_id, $this->userInfo);
                }
                //商品
                $goods = Db::name('qt_product_order')
                    ->field('o.id,r.name as room_name,h.name as hand_card_name,engineer_id')
                    ->alias('o')
                    ->leftJoin('qt_room r', 'r.id = o.room_id')
                    ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                    ->whereIn('hand_card_id', $margeRoom)
                    ->column('o.id');
                $productRes = Db::name('qt_product_order_item')
                    ->field('id as product_order_id,goods_id,goods_name,goods_num,create_time,goods_price,payment_price,is_discount,goods_id,goods_total_price,order_id,sale_id,business_type')
                    ->whereIn('order_id', $goods)
                    ->where('pay_status', '0')
                    ->where(['status'=>'1'])
                    ->select();
                foreach ($productRes as $key => $value) {
                    $productRes[$key]['order_id'] = $value['order_id'];
                    $productRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');
                    $productRes[$key]['room_name'] = Db::name('qt_product_order')
                        ->alias('o')
                        ->leftJoin('qt_room r', 'r.id = o.room_id')
                        ->where('o.id', $value['order_id'])
                        ->value('r.name');
                    $productRes[$key]['is_viper_pay'] = Db::name('qt_goods')->where(['id'=>$value['goods_id']])->value('is_viper_pay');
                }
                $data['project'] = $projectRes;
                $data['goods'] = $productRes;
                $this->result('请求成功', $data, 200);
            } else {
                //单个房间项目
                $project = Db::name('qt_order')
                    ->field('o.id,r.name as room_name,h.name as hand_card_name')
                    ->alias('o')
                    ->leftJoin('qt_room r', 'r.id = o.room_id')
                    ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                    ->where(['hand_card_id' => $getData['hand_card_id'], 'pay_status' => '1'])
                    ->order('o.id desc')
                    ->find();
                $projectRes = Db::name('qt_order_project')
                    ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id')
                    ->where('order_id', $project['id'])
                    ->where('is_change', '1')
                    ->where('pay_status', '0')
                    ->whereNotNull('engineer_id')
                    ->select();
                foreach ($projectRes as $key => $value) {
                    $projectRes[$key]['order_id'] = $project['id'];
                    $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                    $projectRes[$key]['room_name'] = $project['room_name'];
                    $projectRes[$key]['hand_card_name'] = $project['hand_card_name'];
                }

                //插入房费
                $room_data = Db::name('qt_room')->where('id', $getData['room_id'])->find();
                RoomCostService::saveCostOrder($room_data['store_id'], $getData['room_id'], $this->userInfo);
                //商品
                $goods = Db::name('qt_product_order')
                    ->field('o.id,r.name as room_name,h.name as hand_card_name,engineer_id')
                    ->alias('o')
                    ->leftJoin('qt_room r', 'r.id = o.room_id')
                    ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                    ->where(['o.hand_card_id' => $getData['hand_card_id']])
                    ->find();
                $productRes = Db::name('qt_product_order_item')
                    ->field('id as product_order_id,goods_id,goods_name,goods_num,create_time,goods_price,payment_price,is_discount,goods_id,goods_total_price,business_type')
                    ->where('order_id', $goods['id'])
                    ->where('pay_status', '0')
                    ->where(['status'=>'1'])
                    ->select();
                foreach ($productRes as $key => $value) {
                    $productRes[$key]['order_id'] = $goods['id'];
                    $productRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $goods['engineer_id'])->value('real_name');
                    $productRes[$key]['room_name'] = $goods['room_name'];
                    $productRes[$key]['is_viper_pay'] = Db::name('qt_goods')->where(['id'=>$value['goods_id']])->value('is_viper_pay');
                }
                $data['project'] = $projectRes;
                $data['goods'] = $productRes;
                $this->result('请求成功', $data, 200);
            }

        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取用户房间结账支付
     */
    public function pay()
    {

        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $map = [];
            if (empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            if (empty($getData['viper_card_id'])) {
                $getData['viper_card_id'] = '';
            }
            if (empty($getData['viper_card_money'])) {
                $getData['viper_card_money'] = '';
            }
            if (!empty($getData['project_order_total_id'])) {
                $map[] = ['project_order', '=', $getData['project_order_total_id']];
            }
            if (!empty($getData['goods_order_total_id'])) {

                $map[] = ['goods_order', '=', $getData['goods_order_total_id']];
            }
            //备注默认为空
            if (!isset($getData['content']) || empty($getData['content'])) {
                $getData['content'] = '';
            }
            if (!isset($getData['activity_id']) || empty($getData['activity_id'])) {
                $getData['activity_id'] = '';
            }
            if (!isset($getData['cashier_remarks']) || empty($getData['cashier_remarks'])) {
                $getData['cashier_remarks'] = '';
            }
            if (!isset($getData['pay_content']) || empty($getData['pay_content'])) {
                $getData['pay_content'] = '';
            }
            if (!isset($getData['engineer_ids']) || empty($getData['engineer_ids'])) {
                $getData['engineer_ids'] = '';
            }
            if (!isset($getData['project_ids']) || empty($getData['project_ids'])) {
                $getData['project_ids'] = '';
            }

            $room_log = Db::name('qt_room_log')->where('room_id', $getData['room_id'])->order('id desc')->limit(1)->find();
            $find = Db::name('qt_check_out')->where($map)->where('is_revoke', '2')->find();
            if (empty($find)) {
                //构建主结算订单
                $checkOutInsert = [
                    'store_id' => $this->userInfo['store_id'],
                    'room_id' => $getData['room_id'],
                    'engineer_ids' => $getData['engineer_ids'],
                    'project_ids' => $getData['project_ids'],
                    'order_no' => check_order_sn(),
                    'project_order' => $getData['project_order_total_id'],
                    'goods_order' => $getData['goods_order_total_id'],
                    'viper_card_id' => $getData['viper_card_id'],
                    'viper_card_money' => $getData['viper_card_money'],
                    'total_money' => $getData['total_money'],
                    'payment_money' => $getData['payment_money'],
                    'cashier_id' => $this->userInfo['id'],
                    'cashier_time' => time(),
                    'activity_id' => $getData['activity_id'],
                    'cashier_remarks' => $getData['cashier_remarks'],
                    'pay_content' => $getData['pay_content'],
                    'open_room_time' => $room_log['created_time'],
                ];
                $checkOutId = Db::name('qt_check_out')->insertGetId($checkOutInsert);
            } else {
                $checkOutId = $find['id'];
            }

            check_out_pay_all($getData['pay_content'], $checkOutId, $this->userInfo, '2');

            //会员卡结算 card_pay_type 1 会员卡余额 2 次卡 3 月卡
            if (isset($getData['card_data']) && !empty($getData['card_data'])) {
                $cardData = json_decode($getData['card_data'], true);
                foreach ($cardData as $key => $value) {
                    //会员次卡结账
                    if ($value['card_pay_type'] == '2') {
                        $this->pay_number_card($value, $checkOutId);
                        $this->pay_card($value, $checkOutId);
                    } elseif ($value['card_pay_type'] == '3') {
                        //会员月卡结账
                        $this->pay_month_card($value, $checkOutId);
                        $this->pay_card($value, $checkOutId);
                    } elseif ($value['card_pay_type'] == '1') {
                        //会员卡结账
                        $this->pay_card($value, $checkOutId);
                    }
                }
            }

            //项目计算
            $projectRes = json_decode($getData['project'], true);
            $totalProjectPrice = 0;
            $projectInsert = [];
            foreach ($projectRes as $key => $value) {
                $projectInsert[$key] = [
                    'activity_id' => $getData['activity_id'],
                    'link_id' => $value['project_id'],
                    'link_type' => '1',
                    'check_out_id' => $checkOutId,
                    'receivable' => $value['payment_price'],
                    'actual_receipt' => $value['activity_price'],
                    'total_num' => 1,
                ];
                $totalProjectPrice += $value['payment_price'];
                if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                    $value['is_discount'] = 0;
                }
                Db::name('qt_order_project')->where('id', $value['project_order_id'])->update([
                    'payment_price' => $value['payment_price'],
                    'is_discount' => $value['is_discount'],
                    'pay_status' => '1',
                    'pay_time' => time()
                ]);
                //更新提成记录时间
                Db::name('qt_commission_log')
                    ->where(['order_project_id' => $value['project_order_id'], 'type' => '1'])
                    ->update(['updated_time' => time()]);
            }


            //商品数据插入
            $totalGoodsPrice = 0;
            $goodsRes = json_decode($getData['goods'], true);
            if (empty($goodsRes)) {
                $goodsInsert = [];
            }
            foreach ($goodsRes as $key => $value) {
                $goodsInsert[$key] = [
                    'activity_id' => $getData['activity_id'],
                    'link_id' => $value['goods_id'],
                    'link_type' => '2',
                    'check_out_id' => $checkOutId,
                    'receivable' => $value['payment_price'],
                    'actual_receipt' => $value['activity_price'],
                    'total_num' => $value['goods_num'],
                ];
                $totalGoodsPrice += $value['payment_price'];
                if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                    $value['is_discount'] = 0;
                }
                Db::name('qt_product_order_item')->where('id', $value['product_order_id'])->update([
                    'payment_price' => $value['payment_price'],
                    'is_discount' => $value['is_discount'],
                    'pay_status' => '1'
                ]);
                //更新提成记录时间
                Db::name('qt_commission_log')
                    ->where(['order_project_id' => $value['product_order_id'], 'type' => '2'])
                    ->update(['updated_time' => time()]);

            }
            //查询技师是否在房间内
            $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $getData['room_id']])->find();
            //判断房间是否还有未结账的项目子订单如果没有更新总订单
            $checkProjectOrder = Db::name('qt_order_project')->where(['order_id' => $getData['project_order_total_id'], 'pay_status' => '0'])->find();
            if (empty($checkProjectOrder)) {
                //如果技师没在房间内，更新总项目订单的状态
                if (empty($engineerStatus)) {
                    //更新项目总订单
                    Db::name('qt_order')->where('id', $getData['project_order_total_id'])->update([
                        'payment_price' => $totalProjectPrice,
                        'pay_status' => 2,
                        'pay_time' => time(),
                    ]);
                }
            }

            //判断房间是否还有未结账的商品子订单如果没有更新总订单
            $checkPGoodsOrder = Db::name('qt_product_order_item')->where(['order_id' => $getData['goods_order_total_id'], 'pay_status' => '0'])->find();
            if (empty($checkPGoodsOrder)) {
                //更新项目总订单
                Db::name('qt_product_order')->where('id', $getData['goods_order_total_id'])->update([
                    'payment_price' => $totalGoodsPrice,
                    'order_status' => 1,
                    'pay_time' => time(),
                    'pay_status' => 1
                ]);
            }

            //插入结算子表
            $subOrderInsert = array_merge($projectInsert, $goodsInsert);
            Db::name('qt_check_out_item')->insertAll($subOrderInsert);

            //判断房间是否有技师
            $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $getData['room_id']])->find();

            //如果没有，更新房间状态
            if (empty($engineerStatus)) {
                //自动脏房
                if ($this->storeInfo['is_auto_dirty_room'] == '1') {
                    Db::name('qt_room')->where('id', $getData['room_id'])->update(['status_id' => '5']);
                }
            }

            if ($getData['total_money'] == '0') {
                if ($this->storeInfo['is_print_zero_order'] == '1') {
                    //调用结算打印
                    FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
                }
            } else {
                //调用结算打印
                //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
            }
            $result = PrintService::printPcBill($checkOutId,$this->userInfo);
            $this->result('结算成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 获取用户房间单据
     */
    public function bill()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['hand_card_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $where = [];
            //手牌号筛选
            if (isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])) {
                $handCardId = Db::name('qt_hand_card')->where('name', $getData['hand_card_name'])->value('id');
                $where[] = ['hand_card_id', '=', $handCardId];
            }
            //技师号筛选
            if (isset($getData['work_number']) && !empty($getData['work_number'])) {
                $engineerId = Db::name('qt_users')->where('work_number', $getData['work_number'])->value('id');
                $where[] = ['engineer_id', '=', $engineerId];
            }
            //结账筛选
            if (isset($getData['pay_status']) && !empty($getData['pay_status'])) {
                $where[] = ['pay_status', '=', $getData['pay_status']];
            }
            //项目
            $projectRes = Db::name('qt_order_project')
                ->field('id as product_order_id,name as goods_name,old_name as old_goods_name,order_type,created_time,
                engineer_id,start_time,end_time,old_card_id,hand_card_id,old_card_id,old_room_id,is_change,status,is_add,
                created_order_id as create_id,commission,receiver,sale_id,price,pay_status,room_id')
                ->where(['hand_card_id'=>$getData['hand_card_id'],'pay_status'=>'0'])
                ->whereNotIn('status', ['4', '5'])
                ->whereNotNull('engineer_id')
                ->where(['is_change'=>'1','is_delete'=>'2'])
                ->where($where)
                ->select();
            foreach ($projectRes as $key => $value) {
                $projectRes[$key]['work_number'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');//技师
                $projectRes[$key]['sale_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');//销售人
                $projectRes[$key]['room_name'] =Db::name('qt_room')->where('id', $value['room_id'])->value('name');//技师
                $projectRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                $projectRes[$key]['old_card_name'] = Db::name('qt_hand_card')->where('id', $value['old_card_id'])->value('name');
                $projectRes[$key]['old_room'] = Db::name('qt_room')->where('id', $value['old_room_id'])->value('name');//原房间
                $projectRes[$key]['create_name'] = Db::name('qt_users')->where('id', $value['create_id'])->value('real_name');//下单人
                $projectRes[$key]['type'] = '1';//下单人
                $projectRes[$key]['goods_num'] = '1';//数量
            }
            //商品
            $goods = Db::name('qt_product_order')
                ->field('o.id,r.name as room_name,h.name as hand_card_name,engineer_id')
                ->alias('o')
                ->leftJoin('qt_room r', 'r.id = o.room_id')
                ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                ->where(['hand_card_id' => $getData['hand_card_id']])
                ->order('o.id desc')
                ->find();
            $productRes = Db::name('qt_product_order_item')
                ->field('id as product_order_id,goods_name,old_goods_name,old_goods_name,goods_num,create_time,
                create_id,sale_id,old_room_id,commission,receiver,goods_price as price,business_type,pay_status,hand_card_id')
                ->where(['status'=>'1','hand_card_id'=>$getData['hand_card_id'],'pay_status'=>'0'])
                ->where($where)
                ->select();
            foreach ($productRes as $key => $value) {
                $productRes[$key]['engineer_name'] = '';//提成
                $productRes[$key]['sale_name'] = Db::name('qt_users')->where('id', $value['sale_id'])->value('real_name');//销售人
                $productRes[$key]['room_name'] = $goods['room_name'];
                $productRes[$key]['hand_card_name'] = Db::name('qt_hand_card')->where('id', $value['hand_card_id'])->value('name');
                $productRes[$key]['create_name'] = Db::name('qt_users')->where('id', $value['create_id'])->value('real_name');//提成
                $productRes[$key]['old_card_name'] = '';
                $productRes[$key]['status'] = 0;
                $productRes[$key]['is_change'] = '1';
                $productRes[$key]['is_add_work'] = 0;
                $productRes[$key]['order_type'] = '';
                $productRes[$key]['start_time'] = null;
                $productRes[$key]['end_time'] = null;
                $productRes[$key]['old_room'] = Db::name('qt_room')->where('id', $value['old_room_id'])->value('name');//原房间
                $productRes[$key]['type'] = '2';//商品
            }
            $data = array_merge($projectRes, $productRes);
            $this->result('请求成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 更换商品
     */
    public function changeGoods()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['goods_id']) || empty($getData['num']) || empty($getData['product_order_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $find = Db::name('qt_product_order_item')
                ->where(['id' => $getData['product_order_id']])
                ->find();
            if (empty($find)) {
                $this->result('当前商品订单不存在', '', 204);
            }
            if ($find['pay_status'] == '1') {
                $this->result('已结算商品不支持修改', '', 204);
            }
            //构建新的项目
            $newProject = Db::name('qt_goods')->field('id,name,price')->where('id', $getData['goods_id'])->find();
            $updateData = [
                'old_goods_name' => $find['goods_name'],
                'goods_name' => $newProject['name'],
                'goods_price' => $newProject['price'],
                'goods_total_price' => bcmul($newProject['price'], $getData['num'], 2),
                'goods_num' => $getData['num'],
            ];
            try {
                //更新项目订单状态
                Db::name('qt_product_order_item')->where('id', $getData['product_order_id'])->update($updateData);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result('更换失败', '', 204);
            }
            $this->result('更换成功', '', 200);
        }
    }


    /**
     * 删除商品
     */
    public function delGoods()
    {

        if ($this->request->isPost()) {

            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if (empty($getData['product_order_id']) || empty($getData['type'])) {
                $this->result('缺少参数', '', 204);
            }
            if ($getData['type'] == '1') {//删除项目
                $order_project_info = Db::name('qt_order_project')->where(['id' => $getData['product_order_id']])->find();
                if (empty($order_project_info)) {
                    $this->result('当前项目订单不存在', '', 204);
                }
                if ($order_project_info['pay_status'] == '1') {
                    $this->result('已结算项目不允许删除', '', 204);
                }
                //不是加钟的情况下判断当天是否有加钟
                if ($order_project_info['order_type'] != '5') {
                    //查找今天是否有加钟
                    $addFind = Db::name('qt_order_project')
                        ->where('order_id', $order_project_info['order_id'])
                        ->where(['order_type' => '5', 'engineer_id' => $order_project_info['engineer_id']])
                        ->find();
                    if (!empty($addFind)) {
                        $this->result('当前技师有加钟项目，请先删除加钟项目', '', 204);
                    }
                }

                //技师在其他房间并且是上钟状态的不允许删除钟
                $engineerRes = Db::name('qt_users')->where('id', $order_project_info['engineer_id'])->value('work_status');
                $queue = Db::name('qt_order_queue')->where('user_id', $order_project_info['engineer_id'])->value('room_id');
                if ($engineerRes == '4' && $queue != $order_project_info['room_id']) {
                    $this->result('当前技师有加钟项目，请先删除加钟项目', '', 204);
                }
                //删除项目
                if (Db::name('qt_order_project')->where('id', $getData['product_order_id'])->delete()) {
                    //删除项目语音播报
                    SendVoiceMsgService::delProjectVoice($order_project_info['room_id'], $order_project_info['engineer_id'], $order_project_info['name']);
                }

                //查找当前技师是否在其他房间
                if (!empty(Db::name('qt_order_queue')->where(['room_id' => $order_project_info['room_id'], 'user_id' => $order_project_info['engineer_id']])->find())) {
                    //更改技师状态为空闲
                    Db::name('qt_users')->where('id', $order_project_info['engineer_id'])->update(['work_status' => '1']);
                    Db::name('qt_order_queue')->where('user_id', $order_project_info['engineer_id'])
                        ->update([
                            'room_id' => null, 'project_id' => null, 'order_project_id' => null,
                            'order_user_id' => null, 'start_time' => null, 'end_time' => null,
                            'real_time' => null, 'return_time' => time(), 'status' => '1'
                        ]);
                }
            }


            if ($getData['type'] == '2') {

                $product_order_info = Db::name('qt_product_order_item')->where(['id' => $getData['product_order_id']])->find();
                if (empty($product_order_info)) {
                    $this->result('当前商品订单不存在', '', 204);
                }
                if ($product_order_info['pay_status'] == '1') {
                    $this->result('已结算商品不允许删除', '', 204);
                }

                //写云大屏播放语音文本
                $order_item = Db::name('qt_product_order_item')
                    ->alias('oi')
                    ->field(['oi.goods_name', 'oi.goods_num', 'oi.goods_total_price', 'po.room_id', 'po.engineer_id', 'r.name as room_name',])
                    ->leftJoin('qt_product_order po', 'po.id=oi.order_id')
                    ->leftJoin('qt_room r', 'po.room_id=r.id')
                    ->where('oi.store_id', $userInfo['store_id'])
                    ->where('oi.id', $getData['product_order_id'])
                    ->where(['oi.status'=>'1'])
                    ->find();
                if (!empty($order_item)) {
                    $text = $order_item['room_name'] . '  ' . $order_item['goods_name'] . ' 退单';
                    Db::name('qt_send_voice_msg')->insert(['content' => $text, 'type' => 1,'create_time'=>time(),'voice_type'=>2]);
                }

                Db::name('qt_product_order_item')->where('id', $getData['product_order_id'])->update(['status'=>'2']);
            }
            $this->result('删除成功', '', 200);
        }
    }


    /**
     * 修改销售人
     */
    public function changeSale()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['product_order_id']) || empty($getData['sale_id']) || empty($getData['type'])) {
                $this->result('缺少参数', '', 204);
            }
            if ($getData['type'] == '1') {
                $find = Db::name('qt_order_project')
                    ->where(['id' => $getData['product_order_id']])
                    ->find();
                if (empty($find)) {
                    $this->result('当前项目订单不存在', '', 204);
                }
                $update = Db::name('qt_order_project')->where('id', $getData['product_order_id'])->update(['sale_id' => $getData['sale_id']]);
                //更新提出成记录
                Db::name('qt_commission_log')->where('order_project_id', $getData['product_order_id'])->update(['user_id' => $getData['sale_id']]);
            }
            if ($getData['type'] == '2') {
                $find = Db::name('qt_product_order_item')
                    ->where(['id' => $getData['product_order_id']])
                    ->find();
                if (empty($find)) {
                    $this->result('当前商品订单不存在', '', 204);
                }
                $update = Db::name('qt_product_order_item')->where('id', $getData['product_order_id'])->update(['sale_id' => $getData['sale_id']]);
                //更新提出成记录
                Db::name('qt_commission_log')->where('order_project_id', $getData['product_order_id'])->update(['cashier_id' => $getData['sale_id']]);
            }
            if ($update !== false) {
                $this->result('修改成功', '', 200);
            }
            $this->result('修改失败', '', 204);
        }
    }


    /**
     * 修改提成
     */
    public function changeCommission()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['product_order_id']) || empty($getData['type']) || empty($getData['money'])) {
                $this->result('缺少参数', '', 204);
            }
            //项目
            if ($getData['type'] == '1') {
                $find = Db::name('qt_order_project')
                    ->where(['id' => $getData['product_order_id']])
                    ->find();
                if (empty($find)) {
                    $this->result('当前商品项目不存在', '', 204);
                }
                $update = Db::name('qt_order_project')->where('id', $getData['product_order_id'])->update(['commission' => $getData['money']]);
                //修改提成记录
                Db::name('qt_commission_log')
                    ->where(['type' => '1', 'order_project_id' => $getData['product_order_id']])
                    ->update(['receiver' => $getData['money']]);
            }
            if ($getData['type'] == '2') {
                $find = Db::name('qt_product_order_item')
                    ->where(['id' => $getData['product_order_id']])
                    ->find();
                if (empty($find)) {
                    $this->result('当前商品订单不存在', '', 204);
                }
                $update = Db::name('qt_product_order_item')->where('id', $getData['product_order_id'])->update(['receiver' => $getData['money']]);
                //修改提成记录
                Db::name('qt_commission_log')->where(['type' => '2', 'order_project_id' => $getData['product_order_id']])->update(['commission' => $getData['money']]);
            }
            if ($update !== false) {
                $this->result('修改成功', '', 200);
            }
            $this->result('删除失败', '', 204);
        }
    }


    /**
     * 修改上钟类型
     */
    public function changeClock()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['product_order_id']) || empty($getData['order_type'])) {
                $this->result('缺少参数', '', 204);
            }
            //项目
            $find = Db::name('qt_order_project')
                ->where(['id' => $getData['product_order_id']])
                ->find();
            if ($find['order_type'] == $getData['order_type']) {
                $this->result('更改上钟类型与原来一致', '', 204);
            }

            if (empty($find)) {
                $this->result('当前项目订单不存在', '', 204);
            }
            //加钟不能改为其他类型
            if ($find['order_type'] == '5') {
                $this->result('加钟不支持更改为其他类型', '', 204);
            }
            //其他类型不支持改为加钟
            if ($getData['order_type'] == '5') {
                $this->result('不支持更改为加钟', '', 204);
            }
            $update = Db::name('qt_order_project')->where('id', $getData['product_order_id'])->update(['order_type' => $getData['order_type']]);
            //如果是轮排改为加钟的话，并且技师为空闲状态，还原技师的顺序
            if ($find['order_type'] == '1' && $getData['order_type'] == '2') {
                $engineerStatus = Db::name('qt_users')->where('id', $find['engineer_id'])->value('work_status');
                if ($engineerStatus == '1') {
                    //技师状态为空闲时候还原技师顺序
                    $queue = Db::name('qt_order_queue')->where('user_id', $find['engineer_id'])->find();
                    Db::name('qt_order_queue')->where('user_id', $find['engineer_id'])->update(['sort' => $queue['old_sort'], 'old_sort' => $queue['sort']]);
                }
            }
            //如果是轮排改为call钟的话，并且技师为空闲状态，还原技师的顺序
            if ($find['order_type'] == '1' && $getData['order_type'] == '3') {
                $engineerStatus = Db::name('qt_users')->where('id', $find['engineer_id'])->value('work_status');
                if ($engineerStatus == '1') {
                    //技师状态为空闲时候还原技师顺序
                    $queue = Db::name('qt_order_queue')->where('user_id', $find['engineer_id'])->find();
                    Db::name('qt_order_queue')->where('user_id', $find['engineer_id'])->update(['sort' => $queue['old_sort'], 'old_sort' => $queue['sort']]);
                }
            }
            if ($update !== false) {
                $this->result('修改成功', '', 200);
            }
            $this->result('删除失败', '', 204);
        }
    }


    /**
     * 修改时间
     */
    public function changeTime()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['product_order_id']) || empty($getData['time']) || empty($getData['type'])) {
                $this->result('缺少参数', '', 204);
            }
            //项目
            $find = Db::name('qt_order_project')
                ->where(['id' => $getData['product_order_id']])
                ->find();
            if ($getData['type'] == '1') {
                //提前
                $time = $find['start_time'] - ($getData['time'] * 60);
            }
            if ($getData['type'] == '2') {
                //推迟
                $time = $find['start_time'] + ($getData['time'] * 60);
            }
            $update = Db::name('qt_order_project')->where('id', $getData['product_order_id'])->update(['start_time' => $time]);
            //修改当前上钟的时间
            $orderQueue = Db::name('qt_order_queue')->where('user_id', $find['engineer_id'])->find();
            if (!empty($orderQueue['start_time']) && empty($orderQueue['end_time'])) {
                Db::name('qt_order_queue')->where('user_id', $find['engineer_id'])->update(['start_time' => $time]);
            }
            if ($update !== false) {
                $this->result('修改成功', '', 200);
            }
            $this->result('删除失败', '', 204);
        }
    }


    /**
     * 获取次卡详细内容
     */
    public function getNumberTemplate()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_type_id'])) {
                $this->result('缺少参数', '', 204);
            }
            static $couponData = [];
            $resultTemplate = [];
            $resultProject = [];
            $i = 0;
            if (!empty($getData['goods'])) {
                //处理商品抵扣
                $goodsIds = explode(',', $getData['goods']);
                //查询缓存里面是否存在
                foreach ($goodsIds as $key => $value) {
                    $goodsRes = Db::name('qt_goods')->where('id', $value)->find();
                    $resultTemplate[$key]['product_name'] = $goodsRes['name'];
                    $template = Db::name('qt_viper_number_card_template_item')
                        ->field('t.id,t.expire,t.create_time,ci.id as card_item_id')
                        ->alias('tt')
                        ->leftJoin('qt_viper_number_card_template t', 't.id = tt.number_card_template_id')
                        ->leftJoin('qt_viper_card_item ci', 'ci.number_template_id = t.id')
                        ->where('tt.item_type', 'goods')
                        ->where('tt.item_id', $value)
                        ->where('t.viper_type_id', $getData['viper_type_id'])
                        ->group('t.viper_type_id')
                        ->select();
                    if (empty($template)) {
                        //无抵扣次卡
                        $resultTemplate[$key]['product_id'] = 'goods-' . $value;//商品ID
                        $resultTemplate[$key]['id'] = '';//抵扣次卡模板ID
                        $resultTemplate[$key]['name'] = '';//抵扣次卡项目合集
                        $resultTemplate[$key]['num'] = '';//抵扣次卡数量
                        $resultTemplate[$key]['expire'] = '';//抵扣次卡有效期
                        $resultTemplate[$key]['price'] = $goodsRes['price'];
                        $resultTemplate[$key]['card_item_id'] = '';//购买次卡的ID
                    } else {
                        //有抵扣次卡
                        foreach ($template as $k => $v) {
                            $resultTemplate[$key]['id'] = $v['id'];//抵扣次卡模板ID
                            $data = Db::name('qt_viper_number_card_template_item')->where('number_card_template_id', $v['id'])->find();
                            //次卡包含的商品
                            $nameData = Db::name('qt_viper_number_card_template_item')
                                ->alias('item')
                                ->leftJoin('qt_goods g', 'g.id = item.item_id')
                                ->where('item.number_card_template_id', $v['id'])
                                ->where('item.item_type', 'goods')
                                ->column('g.name');
                            $resultTemplate[$key]['name'] = implode(',', $nameData);
                            $resultTemplate[$key]['num'] = '1';
                            $resultTemplate[$key]['expire'] = ($data['expire'] * 86400) + $v['create_time'];
                            $resultTemplate[$key]['price'] = $goodsRes['price'];
                            $resultTemplate[$key]['product_id'] = 'goods-' . $value;//商品ID
                            $resultTemplate[$key]['card_item_id'] = $v['card_item_id'];
                            $couponData[$i]['id'] = $v['id'];
                            $couponData[$i]['name'] = implode(',', $nameData);
                            $couponData[$i]['expire'] = ($data['expire'] * 86400) + $v['create_time'];
                            $couponData[$i]['num'] = '1';
                            $couponData[$i]['card_item_id'] = $v['card_item_id'];
                            $i++;
                        }
                    }
                }
            }
            if (!empty($getData['project'])) {
                //处理项目抵扣
                $projectIds = explode(',', $getData['project']);
                foreach ($projectIds as $key => $value) {
                    $projectRes = Db::name('qt_project')->where('id', $value)->find();
                    $resultProject[$key]['product_name'] = $projectRes['name'];
                    $template = Db::name('qt_viper_number_card_template_item')
                        ->field('t.id,t.expire,t.create_time,ci.id as card_item_id')
                        ->alias('tt')
                        ->leftJoin('qt_viper_number_card_template t', 't.id = tt.number_card_template_id')
                        ->leftJoin('qt_viper_card_item ci', 'ci.number_template_id = t.id')
                        ->where('tt.item_type', 'project')
                        ->where('tt.item_id', $value)
                        ->where('t.viper_type_id', $getData['viper_type_id'])
                        ->group('t.viper_type_id')
                        ->select();
                    if (empty($template)) {
                        //无抵扣次卡
                        $resultProject[$key]['product_id'] = 'project-' . $value;//项目ID
                        $resultProject[$key]['id'] = '';//抵扣次卡模板ID
                        $resultProject[$key]['name'] = '';//抵扣次卡项目合集
                        $resultProject[$key]['num'] = '';//抵扣次卡数量
                        $resultProject[$key]['expire'] = '';//抵扣次卡有效期
                        $resultProject[$key]['price'] = $projectRes['price'];//价格
                        $resultProject[$key]['card_item_id'] = '';//购买次卡的ID
                    } else {
                        //有抵扣次卡
                        foreach ($template as $k => $v) {
                            $resultProject[$key]['id'] = $v['id'];//抵扣次卡模板ID
                            $data = Db::name('qt_viper_number_card_template_item')->where('number_card_template_id', $v['id'])->find();
                            //次卡包含的项目
                            $dataName = Db::name('qt_viper_number_card_template_item')
                                ->alias('item')
                                ->leftJoin('qt_project p', 'p.id = item.item_id')
                                ->where('item.number_card_template_id', $v['id'])
                                ->where('item.item_type', 'project')
                                ->column('p.name');
                            $resultProject[$key]['product_id'] = 'project-' . $value;//项目ID
                            $resultProject[$key]['name'] = implode(',', $dataName);
                            $resultProject[$key]['num'] = '1';
                            $resultProject[$key]['expire'] = ($data['expire'] * 86400) + $data['create_time'];
                            $resultProject[$key]['price'] = $projectRes['price'];
                            $resultProject[$key]['card_item_id'] = $v['card_item_id'];
                            $couponData[$i]['id'] = $v['id'];
                            $couponData[$i]['name'] = implode(',', $dataName);
                            $couponData[$i]['expire'] = ($data['expire'] * 86400) + $data['create_time'];
                            $couponData[$i]['num'] = '1';
                            $couponData[$i]['card_item_id'] = $v['card_item_id'];
                            $i++;
                        }
                    }
                }
            }
            $result = array_merge($resultTemplate, $resultProject);
            $couponData = unique_2d_array_by_key($couponData, 'name');
            $newData ['coupon'] = $couponData;
            $newData ['result'] = $result;
            $this->result('查询成功', $newData, 200);
        }
    }


    /**
     * 获取月卡详细内容
     */
    public function getMonthTemplate()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_type_id'])) {
                $this->result('缺少参数', '', 204);
            }
            static $couponData = [];
            $i = 0;
            $resultTemplate = [];
            if (!empty($getData['goods'])) {
                //处理商品抵扣
                $goodsIds = explode(',', $getData['goods']);
                foreach ($goodsIds as $key => $value) {
                    $goodsRes = Db::name('qt_goods')->where('id', $value)->find();
                    $resultTemplate[$key]['product_name'] = $goodsRes['name'];
                    $template = Db::name('qt_viper_month_card_template_item')
                        ->field('t.id,t.expire,t.create_time,ci.id as card_item_id')
                        ->alias('tt')
                        ->leftJoin('qt_viper_month_card_template t', 't.id = tt.month_template_id')
                        ->leftJoin('qt_viper_card_item ci', 'ci.number_template_id = t.id')
                        ->where('tt.item_type', 'goods')
                        ->where('tt.item_id', $value)
                        ->where('t.viper_type_id', $getData['viper_type_id'])
                        ->group('t.viper_type_id')
                        ->select();
                    if (empty($template)) {
                        //无抵扣月卡
                        $resultTemplate[$key]['product_id'] = 'goods-' . $value;//商品ID
                        $resultTemplate[$key]['id'] = '';//抵扣次卡模板ID
                        $resultTemplate[$key]['name'] = '';//抵扣次卡项目合集
                        $resultTemplate[$key]['num'] = '';//抵扣次卡数量
                        $resultTemplate[$key]['expire'] = '';//抵扣次卡有效期
                        $resultTemplate[$key]['price'] = $goodsRes['price'];
                        $resultTemplate[$key]['card_item_id'] = '';
                    } else {
                        //有抵扣月卡
                        foreach ($template as $k => $v) {
                            $resultTemplate[$key]['id'] = $v['id'];//抵扣次卡模板ID
                            $data = Db::name('qt_viper_month_card_template_item')->where('month_template_id', $v['id'])->find();
                            //月卡包含的商品
                            $nameData = Db::name('qt_viper_month_card_template_item')
                                ->alias('item')
                                ->leftJoin('qt_goods g', 'g.id = item.item_id')
                                ->where('item.number_card_template_id', $v['id'])
                                ->where('item.item_type', 'goods')
                                ->column('g.name');
                            $resultTemplate[$key]['product_id'] = 'goods-' . $value;//商品ID
                            $resultTemplate[$key]['name'] = implode(',', $nameData);
                            $resultTemplate[$key]['num'] = '1';
                            $resultTemplate[$key]['expire'] = $v['expire'];
                            $resultTemplate[$key]['price'] = $goodsRes['price'];
                            $resultTemplate[$key]['card_item_id'] = $v['card_item_id'];
                            $couponData[$i]['name'] = implode(',', $nameData);
                            $couponData[$i]['expire'] = ($v['expire'] * 86400) + $v['create_time'];
                            $couponData[$i]['num'] = '1';
                            $i++;

                        }
                    }
                }
            }
            //处理项目抵扣
            $projectIds = explode(',', $getData['project']);
            foreach ($projectIds as $key => $value) {
                $projectRes = Db::name('qt_project')->where('id', $value)->find();
                $resultProject[$key]['product_name'] = $projectRes['name'];
                $template = Db::name('qt_viper_month_card_template_item')
                    ->field('t.id,t.expire,t.create_time,ci.id as card_item_id')
                    ->alias('tt')
                    ->leftJoin('qt_viper_month_card_template t', 't.id = tt.month_template_id')
                    ->leftJoin('qt_viper_card_item ci', 'ci.number_template_id = t.id')
                    ->where('tt.item_type', 'project')
                    ->where('tt.item_id', $value)
                    ->where('t.viper_type_id', $getData['viper_type_id'])
                    ->group('t.viper_type_id')
                    ->select();
                if (empty($template)) {
                    //无抵扣次卡
                    $resultProject[$key]['product_id'] = 'project-' . $value;//商品ID
                    $resultProject[$key]['id'] = '';//抵扣次卡模板ID
                    $resultProject[$key]['name'] = '';//抵扣次卡项目合集
                    $resultProject[$key]['num'] = '';//抵扣次卡数量
                    $resultProject[$key]['expire'] = '';//抵扣次卡有效期
                    $resultProject[$key]['price'] = $projectRes['price'];//价格
                    $resultProject[$key]['card_item_id'] = '';//次卡ID
                } else {
                    //有抵扣次卡
                    foreach ($template as $k => $v) {
                        $resultProject[$key]['id'] = $v['id'];//抵扣次卡模板ID
                        //月卡包含的项目
                        $dataName = Db::name('qt_viper_month_card_template_item')
                            ->alias('item')
                            ->leftJoin('qt_project p', 'p.id = item.item_id')
                            ->where('item.month_template_id', $v['id'])
                            ->where('item.item_type', 'project')
                            ->column('p.name');
                        $resultProject[$key]['product_id'] = 'project-' . $value;//项目ID
                        $resultProject[$key]['name'] = implode(',', $dataName);
                        $resultProject[$key]['num'] = '1';
                        $resultProject[$key]['expire'] = ($v['expire'] * 86400) + $v['create_time'];
                        $resultProject[$key]['price'] = $projectRes['price'];
                        $resultProject[$key]['card_item_id'] = $v['card_item_id'];//月卡ID
                        $couponData[$i]['name'] = implode(',', $dataName);
                        $couponData[$i]['expire'] = ($v['expire'] * 86400) + $v['create_time'];
                        $couponData[$i]['num'] = '1';
                        $i++;
                    }
                }
            }
            $result = array_merge($resultTemplate, $resultProject);
            $couponData = unique_2d_array_by_key($couponData, 'name');
            $newData ['coupon'] = $couponData;
            $newData ['result'] = $result;
            $this->result('查询成功', $newData, 200);
        }
    }


    /**
     * 会员卡支付
     * @param $data
     */
    public function pay_card($data, $checkOutId)
    {
        $viperCard = Db::name('qt_viper_card')->where(['id' => $data['id']])->find();
        //会员卡输入密码
        $storeInfo = Db::name('qt_store')->where(['id' => $viperCard['store_id']])->find();
        //仅密码支付
        if ($storeInfo['viper_pay_verify_type'] == '2') {
            if ($storeInfo['is_viper_passwd_input'] == '1') {
                //判断密码是否是默认的
                $defaultPass = pwd(config('default_passwd'), $viperCard['salt']);
                if ($defaultPass != $viperCard['passwd']) {
                    //判断密码是否正确
                    $pass = pwd($data['passwd'], $viperCard['salt']);
                    if ($pass != $viperCard['passwd']) {
                        $this->result('密码错误', '', 204);
                    }
                }
            }
        }
        //仅验证码支付
        if ($storeInfo['viper_pay_verify_type'] == '1') {
            $code = $data['code'];
            $sms = new Smscm();
            $status = $sms->check_smscode($viperCard['phone'], $code, '3');
            if ($status['code'] != '200') {
                $this->result('验证码错误', '', 204);
            }
        }
        //验证码加密码
        if ($storeInfo['viper_pay_verify_type'] == '3') {
            if ($storeInfo['is_viper_passwd_input'] == '1') {
                //判断密码是否是默认的
                $defaultPass = pwd(config('default_passwd'), $viperCard['salt']);
                if ($defaultPass != $viperCard['passwd']) {
                    //判断密码是否正确
                    $pass = pwd($data['passwd'], $viperCard['salt']);
                    if ($pass != $viperCard['passwd']) {
                        $this->result('密码错误', '', 204);
                    }
                }
                $code = $data['code'];
                $sms = new Smscm();
                $status = $sms->check_smscode($viperCard['phone'], $code, '3');
                if ($status['code'] != '200') {
                    $this->result('验证码错误', '', 204);
                }
            }
        }
        //验证码加自设密码
        if ($storeInfo['viper_pay_verify_type'] == '4') {
            //判断密码是否正确
            $pass = pwd($data['passwd'], $viperCard['salt']);
            if ($pass != $viperCard['passwd']) {
                $this->result('密码错误', '', 204);
            }
            $code = $data['code'];
            $sms = new Smscm();
            $status = $sms->check_smscode($viperCard['phone'], $code, '3');
            if ($status['code'] != '200') {
                $this->result('验证码错误', '', 204);
            }
        }
        if (empty($viperCard)) {
            $this->result('暂未找到该会员卡', '', 204);
        }
        if ($viperCard['amount'] < $data['pay_amount']) {
            $this->result('会员卡余额不足', '', 204);
        }
        if ($viperCard['give_amount'] < $data['pay_give_amount']) {
            $this->result('会员卡赠送余额不足', '', 204);
        }
        //查找会员
//        $viperUser = Db::name('qt_user_viper')
//            ->field('u.*')
//            ->alias('u')
//            ->leftJoin('qt_viper_card c', 'u.id  = c.user_id')
//            ->where('c.id', $data['id'])
//            ->find();
        try {
            //更新会员
            //Db::name('qt_user_viper')->where('id', $viperUser['id'])->setDec('money', $data['pay_amount']);
            //更新余额
            Db::name('qt_viper_card')->where('id', $viperCard['id'])->setDec('amount', $data['pay_amount']);
            //更新赠送余额
            Db::name('qt_viper_card')->where('id', $viperCard['id'])->setDec('give_amount', $data['pay_give_amount']);
            //更新消费金额
            Db::name('qt_viper_card')->where('id', $viperCard['id'])->setInc('consumption_amount', ($data['pay_amount'] + $data['pay_give_amount']));
            //更新会员最后消费时间
            Db::name('qt_viper_card')->where('id', $viperCard['id'])->update(['end_consumption_time' => time()]);
            //插入会员消费记录
            $after = $viperCard['amount'] - $data['pay_amount'];
            $afterGive = $viperCard['amount'] - $data['pay_give_amount'];
            $log[0] = [
                'viper_card_id' => $viperCard['id'],
                'order_id' => $checkOutId,
                'type' => '3',
                'money' => $data['pay_amount'],
                'create_time' => time(),
                'content' => '',
                'check' => '2',
                'flag' => '1',
                'after_money' => $after,
            ];
            if (!empty($data['pay_give_amount'])) {
                $log[1] = [
                    'viper_card_id' => $viperCard['id'],
                    'type' => '3',
                    'order_id' => $checkOutId,
                    'money' => $data['pay_give_amount'],
                    'create_time' => time(),
                    'content' => '',
                    'check' => '2',
                    'flag' => '3',
                    'after_money' => $after,
                ];
            }
            Db::name('qt_viper_money_log')->insertAll($log);
            check_out_card_pay_all($viperCard['id'],($data['pay_amount'] + $data['pay_give_amount']), $checkOutId, $this->userInfo, '2', $data['pay_amount'] ,$data['pay_give_amount'],$after,$afterGive);
            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->result('消费失败', '', 204);
        }
    }

    /**
     * 处理次卡消费
     * @param $data [会员卡消费数据]
     * @param $checkOutID [结账单据ID]
     */
    public function pay_number_card($data, $checkOutID)
    {
        //查询会员次卡信息
        $viperUser = Db::name('qt_viper_card')
            ->field('id,store_id')
            ->where('id', $data['id'])
            ->find();
        foreach ($data['template_data'] as $key => $value) {
            $number = Db::name('qt_viper_number_card_template_item')->where(['number_card_template_id' => $value['template_id']])->value('number');
            $userUseNumber = Db::name('qt_viper_card_use_log')->where(['card_type' => '1', 'viper_card_id' => $data['id'], 'template_id' => $value['template_id']])->sum('number');
            $userUseNumber = intval($userUseNumber);
            if (($userUseNumber + 1) > $number) {
                $this->result('会员卡超出使用数量', '', 204);
            }
            $product = explode('-', $value['product_id']);
            if ($product[0] == '1') {
                //项目
                $itemPrice = Db::name('qt_project')->where(['id' => $product[1]])->value('price');
            } else {
                //项目
                $itemPrice = Db::name('qt_goods')->where(['id' => $product[1]])->value('price');
            }
            //插入会员卡使用记录
            $insert = [
                'user_id' => $viperUser['id'],
                'store_id' => $viperUser['store_id'],
                'viper_card_id' => $data['id'],
                'template_id' => $value['template_id'],
                'order_id' => $checkOutID,
                'item_type' => $product[0],
                'item_id' => $product[1],
                'item_price' => $itemPrice,
                'number' => $value['num'],
                'create_time' => time(),
                'card_type' => '1',
                'card_item_id' => $value['card_item_id'],
            ];
            Db::name('qt_viper_card_use_log')->insert($insert);
            //更新会员卡次卡使用次数
            Db::name('qt_viper_card_item')->where(['id' => $value['card_item_id']])->setInc('use_number', '1');

        }
        //更新会员最后消费时间
        Db::name('qt_viper_card')->where('id', $viperUser['id'])->update(['end_consumption_time' => time()]);

    }


    /**
     * 处理月卡消费
     * @param $data
     */
    public function pay_month_card($data, $checkOutID)
    {
        //查询会员月卡信息
        $viperUser = Db::name('qt_viper_card')
            ->field('id,store_id')
            ->where('id', $data['id'])
            ->find();
        foreach ($data['template_data'] as $key => $value) {
            $template = Db::name('qt_viper_month_card_template')->where('id', $value['template_id'])->find();
            $userMonthStatus = Db::name('qt_viper_card_item')
                ->where(['viper_card_id' => $value['id'], 'month_template_id' => $value['template_id'], 'status' => '1'])
                ->find();
            if (empty($userMonthStatus)) {
                $this->result('该月卡已经禁止使用', '', 204);
            }
            if ($template['type'] == '1') {
                //每天
                $userUseNumber = Db::name('qt_viper_card_use_log')
                    ->where(['card_type' => '2', 'viper_card_id' => $value['id'], 'template_id' => $value['template_id']])
                    ->whereTime('create_time', 'today')
                    ->sum('number');
                if (($userUseNumber + 1) > $template['hz']) {
                    $this->result('会员卡超出使用频率', '', 204);
                }
            }
            if ($template['type'] == '2') {
                //每月
                $userUseNumber = Db::name('qt_viper_card_use_log')
                    ->where(['card_type' => '2', 'viper_card_id' => $value['id'], 'template_id' => $value['template_id']])
                    ->whereTime('create_time', 'm')
                    ->sum('number');
                if (($userUseNumber + 1) > $template['hz']) {
                    $this->result('会员卡超出使用频率', '', 204);
                }
            }
            if ($template['type'] == '3') {
                //每年
                $userUseNumber = Db::name('qt_viper_card_use_log')
                    ->where(['card_type' => '2', 'viper_card_id' => $value['id'], 'template_id' => $value['template_id']])
                    ->whereTime('create_time', 'y')
                    ->sum('number');
                if (($userUseNumber + 1) > $template['hz']) {
                    $this->result('会员卡超出使用频率', '', 204);
                }
            }
            $product = explode('-', $value['product_id']);
            if ($product[0] == '1') {
                //项目
                $itemPrice = Db::name('qt_project')->where(['id' => $product[1]])->value('price');
            } else {
                //项目
                $itemPrice = Db::name('qt_goods')->where(['id' => $product[1]])->value('price');
            }
            //插入会员卡使用记录
            $insert = [
                'user_id' => $viperUser['id'],
                'store_id' => $viperUser['store_id'],
                'viper_card_id' => $data['id'],
                'template_id' => $value['template_id'],
                'order_id' => $checkOutID,
                'item_type' => $product[0],
                'item_id' => $product[1],
                'item_price' => $itemPrice,
                'number' => $value['num'],
                'create_time' => time(),
                'card_type' => '2',
                'card_item_id' => $value['card_item_id'],
            ];
            Db::name('qt_viper_card_use_log')->insert($insert);
            //更新会员卡次卡使用次数
            Db::name('qt_viper_card_item')->where(['id' => $value['card_item_id']])->setInc('use_number', '1');
        }
        //更新会员最后消费时间
        Db::name('qt_viper_card')->where('id', $viperUser['id'])->update(['end_consumption_time' => time()]);


    }

    /**
     * 验证会员卡
     * @param $type [类型] [1密码，2验证码]
     * @param $code [密码或者验证码]
     * @param $cardId [会员卡ID]
     */
    public function checkPass($passwd, $code, $cardId)
    {
        $cardRes = Db::name('qt_viper_card')->field('id,passwd')->where('id', $cardId)->find();
        if (!empty($passwd)) {
            $newPass = pwd($code, $cardRes['salt']);
            if ($newPass != $cardRes['passwd']) {
                $this->result('密码错误', '', 204);
            }
        } elseif (!empty($code)) {
            $sms = new Smscm();
            $result = $sms->check_smscode($cardRes['mobile'], $code, '3');
            if ($result['code'] != '200') {
                $this->result('验证码错误', '', 204);
            }
        }
    }


    /**
     * 获取会员卡支付比例
     */
    public function viperCardDiscount()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_type_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $data = Db::name('qt_viper_type')->field('id,amount_percentage,give_amount_percentage')->where('id', $getData['viper_type_id'])->find();
            $this->result('查询成功', $data, 200);
        }
    }


    /**
     * 获取房间项目
     */
    public function project()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            //项目
            $project = Db::name('qt_order')
                ->field('o.id,r.name as room_name,h.name as hand_card_name')
                ->alias('o')
                ->leftJoin('qt_room r', 'r.id = o.room_id')
                ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                ->where(['room_id' => $getData['room_id'], 'pay_status' => '1'])
                ->order('o.id desc')
                ->find();
            $projectRes = Db::name('qt_order_project')
                ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id,status,start_time,real_end_time,created_order_id')
                ->where('order_id', $project['id'])
                ->where('is_change', '1')
                ->select();
            foreach ($projectRes as $key => $value) {
                $projectRes[$key]['order_id'] = $project['id'];
                $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                $projectRes[$key]['room_name'] = $project['room_name'];
                $projectRes[$key]['hand_card_name'] = $project['hand_card_name'];
                $projectRes[$key]['create_name'] = Db::name('qt_users')->where('id', $value['created_order_id'])->value('real_name');
            }
            $this->result('查询成功', $projectRes, 200);
        }
    }


    /**
     * 计算折扣
     */
    public function discount()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['active_id'])) {
                $this->result('缺少参数', '', 204);
            }
            //项目
            if (!empty($getData['project'])) {
                $projectRes = json_decode($getData['project'], true);
                foreach ($projectRes as $key => $value) {
                    //查询项目是否有活动价
                    $dis = Db::name('qt_data_activity_item')
                        ->where(['item_type' => 'project', 'item_id' => $value['project_id'], 'activity_id' => $getData['active_id']])
                        ->find();
                    if (!empty($dis)) {
                        if (isset($getData['viper_card_type_id']) && !empty($getData['viper_card_type_id'])) {
                            $vip = Db::name('qt_data_activity_item_viper')->where(['activity_item_id' => $dis['id'], 'viper_card_type_id' => $getData['viper_card_type_id']])->find();
                        } else {
                            $vip = Db::name('qt_data_activity_item_viper')->where(['activity_item_id' => $dis['id']])->find();
                        }
                        if (empty($vip)) {
                            $viper_price = $value['price'];
                            $viper_add_block_price = '';
                        } else {
                            $viper_price = $vip['viper_price'];
                            $viper_add_block_price = $vip['viper_add_block_price'];
                        }
                        $projectRes[$key]['activity_price'] = $dis['activity_price'];
                        $projectRes[$key]['add_block_price'] = $dis['add_block_price'];
                        $projectRes[$key]['viper_price'] = $viper_price;
                        $projectRes[$key]['viper_add_block_price'] = $viper_add_block_price;
                    } else {
                        $projectRes[$key]['activity_price'] = $value['price'];
                        $projectRes[$key]['add_block_price'] = '';
                        $projectRes[$key]['viper_price'] = $value['price'];
                        $projectRes[$key]['viper_add_block_price'] = '';
                    }

                }
            } else {
                $projectRes = [];
            }
            //商品
            if (!empty($getData['goods'])) {
                $goodsRes = json_decode($getData['goods'], true);
                foreach ($goodsRes as $key => $value) {
                    //查询项目是否有活动价
                    $dis = Db::name('qt_data_activity_item')
                        ->where(['item_type' => 'goods', 'item_id' => $value['goods_id'], 'activity_id' => $getData['active_id']])
                        ->find();
                    if (!empty($dis)) {
                        $goodsRes[$key]['activity_price'] = $dis['activity_price'];
                        $goodsRes[$key]['add_block_price'] = $dis['add_block_price'];

                    } else {
                        $goodsRes[$key]['activity_price'] = $value['goods_price'];
                        $goodsRes[$key]['add_block_price'] = '';
                    }
                }
            } else {
                $goodsRes = [];
            }
            $result['project'] = $projectRes;
            $result['goods'] = $goodsRes;
            $this->result('查询成功', $result, 200);
        }
    }


    /**
     * 计算会员价格
     */
    public function vip_discount()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['viper_type_id'])) {
                $this->result('缺少参数', '', 204);
            }
            //项目
            if (!empty($getData['project'])) {
                $projectRes = json_decode($getData['project'], true);
                foreach ($projectRes as $key => $value) {
                    //查询项目是否有活动价
                    $dis = Db::name('qt_viper_activity_project')
                        ->where(['project_id' => $value['project_id'], 'viper_type_id' => $getData['viper_type_id']])
                        ->find();
                    if (!empty($dis)) {
                        //判断是否有时段价格
                        $projectRes[$key]['viper_price'] = $dis['viper_price'];
                        $projectRes[$key]['add_block_price'] = $dis['add_block_price'];
                    } else {
                        $projectRes[$key]['viper_price'] = $value['price'];
                        $projectRes[$key]['add_block_price'] = $value['price'];
                    }
                }
            } else {
                $projectRes = [];
            }
            //商品
            if (!empty($getData['goods'])) {
                $goodsRes = json_decode($getData['goods'], true);
                foreach ($goodsRes as $key => $value) {
                    //查询项目是否有活动价
                    $dis = Db::name('qt_viper_activity_goods')
                        ->where(['product_id' => $value['goods_id'], 'viper_type_id' => $getData['viper_type_id']])
                        ->find();
                    if (!empty($dis)) {
                        //判断是否有时段价格
                        $goodsRes[$key]['viper_price'] = $dis['viper_price'];
                    } else {
                        $goodsRes[$key]['viper_price'] = $value['goods_price'];
                    }
                }
            } else {
                $goodsRes = [];
            }
            $result['project'] = $projectRes;
            $result['goods'] = $goodsRes;
            $this->result('查询成功', $result, 200);
        }
    }


    /**
     * 订单挂账
     */
    public function credit()
    {

        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $map = [];
            if (empty($getData['room_id'])) {
                $this->result('缺少参数', '', 204);
            }
            if (empty($getData['viper_card_id'])) {
                $getData['viper_card_id'] = '';
            }
            if (empty($getData['viper_card_money'])) {
                $getData['viper_card_money'] = '';
            }
            if (!empty($getData['project_order_total_id'])) {
                $map[] = ['project_order', '=', $getData['project_order_total_id']];
            }
            if (!empty($getData['goods_order_total_id'])) {

                $map[] = ['goods_order', '=', $getData['goods_order_total_id']];
            }
            //备注默认为空
            if (!isset($getData['content']) || empty($getData['content'])) {
                $getData['content'] = '';
            }
            if (!isset($getData['activity_id']) || empty($getData['activity_id'])) {
                $getData['activity_id'] = '';
            }
            if (!isset($getData['cashier_remarks']) || empty($getData['cashier_remarks'])) {
                $getData['cashier_remarks'] = '';
            }
            if (!isset($getData['pay_content']) || empty($getData['pay_content'])) {
                $getData['pay_content'] = '';
            }
            if (!isset($getData['engineer_ids']) || empty($getData['engineer_ids'])) {
                $getData['engineer_ids'] = '';
            }
            if (!isset($getData['project_ids']) || empty($getData['project_ids'])) {
                $getData['project_ids'] = '';
            }
            $find = Db::name('qt_check_out')->where($map)->where('is_revoke', '2')->find();
            if (empty($find)) {
                //构建主结算订单
                $checkOutInsert = [
                    'store_id' => $this->userInfo['store_id'],
                    'room_id' => $getData['room_id'],
                    'engineer_ids' => $getData['engineer_ids'],
                    'project_ids' => $getData['project_ids'],
                    'order_no' => check_order_sn(),
                    'project_order' => $getData['project_order_total_id'],
                    'goods_order' => $getData['goods_order_total_id'],
                    'viper_card_id' => $getData['viper_card_id'],
                    'viper_card_money' => $getData['viper_card_money'],
                    'total_money' => $getData['total_money'],
                    'payment_money' => $getData['payment_money'],
                    'cashier_id' => $this->userInfo['id'],
                    'cashier_time' => time(),
                    'activity_id' => $getData['activity_id'],
                    'cashier_remarks' => $getData['cashier_remarks'],
                    'pay_content' => $getData['pay_content'],
                    'order_type' => '2',
                ];
                $checkOutId = Db::name('qt_check_out')->insertGetId($checkOutInsert);
            } else {
                $checkOutId = $find['id'];
            }
            //项目计算
            $projectRes = json_decode($getData['project'], true);
            $totalProjectPrice = 0;
            $projectInsert = [];
            foreach ($projectRes as $key => $value) {
                $projectInsert[$key] = [
                    'activity_id' => $getData['activity_id'],
                    'link_id' => $value['project_id'],
                    'link_type' => '1',
                    'check_out_id' => $checkOutId,
                    'receivable' => $value['payment_price'],
                    'actual_receipt' => $value['activity_price'],
                ];
                $totalProjectPrice += $value['payment_price'];
                if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                    $value['is_discount'] = 0;
                }
                Db::name('qt_order_project')->where('id', $value['project_order_id'])->update([
                    'payment_price' => $value['payment_price'],
                    'is_discount' => $value['is_discount'],
                    'pay_status' => '2',
                    'pay_time' => time()
                ]);
            }
            //商品数据插入
            $totalGoodsPrice = 0;
            $goodsRes = json_decode($getData['goods'], true);
            if (empty($goodsRes)) {
                $goodsInsert = [];
            }
            foreach ($goodsRes as $key => $value) {
                $goodsInsert[$key] = [
                    'activity_id' => $getData['activity_id'],
                    'link_id' => $value['goods_id'],
                    'link_type' => '2',
                    'check_out_id' => $checkOutId,
                    'receivable' => $value['payment_price'],
                    'actual_receipt' => $value['activity_price'],
                ];
                $totalGoodsPrice += $value['payment_price'];
                if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                    $value['is_discount'] = 0;
                }
                Db::name('qt_product_order_item')->where('id', $value['product_order_id'])->update([
                    'payment_price' => $value['payment_price'],
                    'is_discount' => $value['is_discount'],
                    'pay_status' => '2'
                ]);
            }
            //查询技师是否在房间内
            $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $getData['room_id']])->find();
            //判断房间是否还有未结账的项目子订单如果没有更新总订单
            $checkProjectOrder = Db::name('qt_order_project')->where(['order_id' => $getData['project_order_total_id'], 'pay_status' => '0'])->find();
            if (empty($checkProjectOrder)) {
                //如果技师没在房间内，更新总项目订单的状态
                if (empty($engineerStatus)) {
                    //更新项目总订单
                    Db::name('qt_order')->where('id', $getData['project_order_total_id'])->update([
                        'payment_price' => $totalProjectPrice,
                        'pay_status' => 2,
                        'pay_time' => time(),
                    ]);
                }
            }
            //判断房间是否还有未结账的商品子订单如果没有更新总订单
            $checkPGoodsOrder = Db::name('qt_product_order_item')->where(['order_id' => $getData['goods_order_total_id'], 'pay_status' => '0'])->find();
            if (empty($checkPGoodsOrder)) {
                //更新项目总订单
                Db::name('qt_product_order')->where('id', $getData['goods_order_total_id'])->update([
                    'payment_price' => $totalGoodsPrice,
                    'order_status' => 1,
                    'pay_time' => time(),
                    'pay_status' => 1
                ]);
            }
            //插入结算子表
            $subOrderInsert = array_merge($projectInsert, $goodsInsert);
            Db::name('qt_check_out_item')->insertAll($subOrderInsert);
            //判断房间是否有技师
            $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $getData['room_id']])->find();
            //如果没有，更新房间状态
            if (empty($engineerStatus)) {
                //自动脏房
                if ($this->storeInfo['is_auto_dirty_room'] == '1') {
                    Db::name('qt_room')->where('id', $getData['room_id'])->update(['status_id' => '5']);
                }
            }
            //调用结算打印
            //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
            //插入挂账信息
            $insertCheng = [];
            if (empty($getData['charge_id'])) {
                $insertCheng = [
                    'store_id' => $this->userInfo['store_id'],
                    'user_id' => $this->userInfo['id'],
                    'company_id' => $getData['company_id'],
                    'name' => $getData['name'],
                    'phone' => $getData['phone'],
                    'total_price' => $getData['total_money'],
                    'payment_price' => 0,
                    'content' => '',
                    'create_time' => time(),
                    'update_time' => time(),
                ];

            }
            if(!empty($insertCheng)){
                //插入挂账订单
                $chargeID = Db::name('qt_charge')->insertGetId($insertCheng);
            }
            try {
                Db::startTrans();
                if (!empty($getData['charge_id'])) {
                    $insertItemData = [
                        'user_id' => $this->userInfo['id'],
                        'charge_id' => $getData['charge_id'],
                        'check_out_id' => $checkOutId,
                        'content' => $getData['charge_content'],
                    ];
                    //增加金额
                    Db::name('qt_charge')->where('id', $getData['charge_id'])->setInc('total_price', $getData['total_money']);
                    //更新最后挂账时间
                    Db::name('qt_charge')->where('id', $getData['charge_id'])->update(['update_time'=>time()]);
                } else {
                    $insertItemData = [
                        'user_id' => $this->userInfo['id'],
                        'charge_id' => $chargeID,
                        'check_out_id' => $checkOutId,
                        'content' => $getData['charge_content'],
                    ];
                }
                //更新订单状态
                Db::name('qt_charge_item')->insert($insertItemData);
                Db::commit();
            } catch (Exception $exception) {
                Db::rollback();
                $this->result('挂账失败', '', 204);
            }
            $this->result('挂账成功', '', 200);
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 用户挂账结账列表
     */
    public function credit_bill()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['check_out_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $checkOutIds = explode(',',$getData['check_out_id']);
            $checkOutData = Db::name('qt_check_out')->field('id,project_order,goods_order')->whereIn('id',$checkOutIds)->select();
            $projectOrder = [];//项目订单ID合集
            $goodsOrder = [];//商品订单ID合集
            foreach ($checkOutData as $key=>$value){
                $projectOrder[$key] = $value['project_order'];
                $goodsOrder[$key] = $value['goods_order'];
            }
            $project = Db::name('qt_order')
                ->field('o.id,r.name as room_name,h.name as hand_card_name')
                ->alias('o')
                ->leftJoin('qt_room r', 'r.id = o.room_id')
                ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                ->whereIn('o.id',$projectOrder)
                ->order('o.id desc')
                ->find();
            $projectRes = Db::name('qt_order_project')
                ->field('id as project_order_id,name as project_name,order_type,created_time,price,payment_price,engineer_id,project_id')
                ->where('order_id', $project['id'])
                ->where('is_change', '1')
                ->where('pay_status', '2')
                ->whereNotNull('engineer_id')
                ->select();
            foreach ($projectRes as $key => $value) {
                $projectRes[$key]['order_id'] = $project['id'];
                $projectRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $value['engineer_id'])->value('work_number');
                $projectRes[$key]['room_name'] = $project['room_name'];
                $projectRes[$key]['hand_card_name'] = $project['hand_card_name'];
            }
            //商品
            $goods = Db::name('qt_product_order')
                ->field('o.id,r.name as room_name,h.name as hand_card_name,engineer_id')
                ->alias('o')
                ->leftJoin('qt_room r', 'r.id = o.room_id')
                ->leftJoin('qt_hand_card h', 'h.id = o.hand_card_id')
                ->whereIn('o.id',$goodsOrder)
                ->find();
            $productRes = Db::name('qt_product_order_item')
                ->field('id as product_order_id,goods_id,goods_name,goods_num,create_time,goods_price,payment_price,is_discount,goods_id,goods_total_price,business_type')
                ->where('order_id', $goods['id'])
                ->where('pay_status', '2')
                ->where(['status'=>'1'])
                ->select();
            foreach ($productRes as $key => $value) {
                $productRes[$key]['order_id'] = $goods['id'];
                $productRes[$key]['engineer_name'] = Db::name('qt_users')->where('id', $goods['engineer_id'])->value('real_name');
                $productRes[$key]['room_name'] = $goods['room_name'];
                $productRes[$key]['is_viper_pay'] = Db::name('qt_goods')->where(['id'=>$value['goods_id']])->value('is_viper_pay');
            }
            $data['project'] = $projectRes;
            $data['goods'] = $productRes;
            $this->result('请求成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 挂账结账支付
     */
    public function credit_pay()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $map = [];
            if (empty($getData['viper_card_id'])) {
                $getData['viper_card_id'] = '';
            }
            if (empty($getData['viper_card_money'])) {
                $getData['viper_card_money'] = '';
            }
            if (!empty($getData['project_order_total_id'])) {
                $map[] = ['project_order', '=', $getData['project_order_total_id']];
            }
            if (!empty($getData['goods_order_total_id'])) {

                $map[] = ['goods_order', '=', $getData['goods_order_total_id']];
            }
            //备注默认为空
            if (!isset($getData['content']) || empty($getData['content'])) {
                $getData['content'] = '';
            }
            if (!isset($getData['activity_id']) || empty($getData['activity_id'])) {
                $getData['activity_id'] = '';
            }
            if (!isset($getData['cashier_remarks']) || empty($getData['cashier_remarks'])) {
                $getData['cashier_remarks'] = '';
            }
            if (!isset($getData['pay_content']) || empty($getData['pay_content'])) {
                $getData['pay_content'] = '';
            }
            if (!isset($getData['engineer_ids']) || empty($getData['engineer_ids'])) {
                $getData['engineer_ids'] = '';
            }
            if (!isset($getData['project_ids']) || empty($getData['project_ids'])) {
                $getData['project_ids'] = '';
            }
            $room_log = Db::name('qt_room_log')->where('room_id', $getData['room_id'])->order('id desc')->limit(1)->find();
            $find = Db::name('qt_check_out')->where($map)->where('is_revoke', '2')->find();
            if (empty($find)) {
                //构建主结算订单
                $checkOutInsert = [
                    'store_id' => $this->userInfo['store_id'],
                    'room_id' => $getData['room_id'],
                    'engineer_ids' => $getData['engineer_ids'],
                    'project_ids' => $getData['project_ids'],
                    'order_no' => check_order_sn(),
                    'project_order' => $getData['project_order_total_id'],
                    'goods_order' => $getData['goods_order_total_id'],
                    'viper_card_id' => $getData['viper_card_id'],
                    'viper_card_money' => $getData['viper_card_money'],
                    'total_money' => $getData['total_money'],
                    'payment_money' => $getData['payment_money'],
                    'cashier_id' => $this->userInfo['id'],
                    'cashier_time' => time(),
                    'activity_id' => $getData['activity_id'],
                    'cashier_remarks' => $getData['cashier_remarks'],
                    'pay_content' => $getData['pay_content'],
                    'open_room_time' => $room_log['created_time'],
                ];
                $checkOutId = Db::name('qt_check_out')->insertGetId($checkOutInsert);
            } else {
                $checkOutId = $find['id'];
            }

            check_out_pay_all($getData['pay_content'], $checkOutId, $this->userInfo, '2');

            //会员卡结算 card_pay_type 1 会员卡余额 2 次卡 3 月卡
            if (isset($getData['card_data']) && !empty($getData['card_data'])) {
                $cardData = json_decode($getData['card_data'], true);
                foreach ($cardData as $key => $value) {
                    //会员次卡结账
                    if ($value['card_pay_type'] == '2') {
                        $this->pay_number_card($value, $checkOutId);
                        $this->pay_card($value, $checkOutId);
                    } elseif ($value['card_pay_type'] == '3') {
                        //会员月卡结账
                        $this->pay_month_card($value, $checkOutId);
                        $this->pay_card($value, $checkOutId);
                    } elseif ($value['card_pay_type'] == '1') {
                        //会员卡结账
                        $this->pay_card($value, $checkOutId);
                    }
                }
            }
            //项目计算
            $projectRes = json_decode($getData['project'], true);
            $totalProjectPrice = 0;
            $projectInsert = [];
            foreach ($projectRes as $key => $value) {
                $projectInsert[$key] = [
                    'activity_id' => $getData['activity_id'],
                    'link_id' => $value['project_id'],
                    'link_type' => '1',
                    'check_out_id' => $checkOutId,
                    'receivable' => $value['payment_price'],
                    'actual_receipt' => $value['activity_price'],
                    'total_num' => 1,
                ];
                $totalProjectPrice += $value['payment_price'];
                if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                    $value['is_discount'] = 0;
                }
                Db::name('qt_order_project')->where('id', $value['project_order_id'])->update([
                    'payment_price' => $value['payment_price'],
                    'is_discount' => $value['is_discount'],
                    'pay_status' => '1',
                    'pay_time' => time()
                ]);
                //更新提成记录时间
                Db::name('qt_commission_log')
                    ->where(['order_project_id' => $value['project_order_id'], 'type' => '1'])
                    ->update(['updated_time' => time()]);
            }
            //商品数据插入
            $totalGoodsPrice = 0;
            $goodsRes = json_decode($getData['goods'], true);
            if (empty($goodsRes)) {
                $goodsInsert = [];
            }
            foreach ($goodsRes as $key => $value) {
                $goodsInsert[$key] = [
                    'activity_id' => $getData['activity_id'],
                    'link_id' => $value['goods_id'],
                    'link_type' => '2',
                    'check_out_id' => $checkOutId,
                    'receivable' => $value['payment_price'],
                    'actual_receipt' => $value['activity_price'],
                    'total_num' => $value['goods_num'],
                ];
                $totalGoodsPrice += $value['payment_price'];
                if (!isset($value['is_discount']) || empty($value['is_discount'])) {
                    $value['is_discount'] = 0;
                }
                Db::name('qt_product_order_item')->where('id', $value['product_order_id'])->update([
                    'payment_price' => $value['payment_price'],
                    'is_discount' => $value['is_discount'],
                    'pay_status' => '1'
                ]);
                //更新提成记录时间
                Db::name('qt_commission_log')
                    ->where(['order_project_id' => $value['product_order_id'], 'type' => '2'])
                    ->update(['updated_time' => time()]);

            }
            //查询技师是否在房间内
            $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $getData['room_id']])->find();
            //判断房间是否还有未结账的项目子订单如果没有更新总订单
            $checkProjectOrder = Db::name('qt_order_project')->where(['order_id' => $getData['project_order_total_id'], 'pay_status' => '0'])->find();
            if (empty($checkProjectOrder)) {
                //如果技师没在房间内，更新总项目订单的状态
                if (empty($engineerStatus)) {
                    //更新项目总订单
                    Db::name('qt_order')->where('id', $getData['project_order_total_id'])->update([
                        'payment_price' => $totalProjectPrice,
                        'pay_status' => 2,
                        'pay_time' => time(),
                    ]);
                }
            }
            //判断房间是否还有未结账的商品子订单如果没有更新总订单
            $checkPGoodsOrder = Db::name('qt_product_order_item')->where(['order_id' => $getData['goods_order_total_id'], 'pay_status' => '0'])->find();
            if (empty($checkPGoodsOrder)) {
                //更新项目总订单
                Db::name('qt_product_order')->where('id', $getData['goods_order_total_id'])->update([
                    'payment_price' => $totalGoodsPrice,
                    'order_status' => 1,
                    'pay_time' => time(),
                    'pay_status' => 1
                ]);
            }
            //插入结算子表
            $subOrderInsert = array_merge($projectInsert, $goodsInsert);
            Db::name('qt_check_out_item')->insertAll($subOrderInsert);
            //判断房间是否有技师
            $engineerStatus = Db::name('qt_order_queue')->where(['room_id' => $getData['room_id']])->find();
            //如果没有，更新房间状态
            if (empty($engineerStatus)) {
                //自动脏房
                if ($this->storeInfo['is_auto_dirty_room'] == '1') {
                    Db::name('qt_room')->where('id', $getData['room_id'])->update(['status_id' => '5']);
                }
            }
            if ($getData['total_money'] == '0') {
                if ($this->storeInfo['is_print_zero_order'] == '1') {
                    //调用结算打印
                    FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
                }
            } else {
                //调用结算打印
                //FeiEPrintService::printPhoneBill($checkOutId,$this->userInfo);
            }
            $result = PrintService::printPcBill($checkOutId,$this->userInfo);
            $this->result('结算成功', $result, 200);
        }
        $this->result('无效的请求', '', 204);
    }



}
